import Vue from 'vue';
import VueRouter from 'vue-router';
import iView from 'view-design';

import util from '@/libs/util'

import Setting from '@/setting';

import store from '@/store/index';

// 路由数据
import routes from './routes';

Vue.use(VueRouter);

//当前环境
const environments = `${process.env.VUE_APP_ENV}` || 'production'

//路由的base path
export const routerBasePath = {
    development: {
        path: ""
    },
    devPub: {
        path: ""
    },
    pretest: {
        path: ""
    },
    test: {
        path: Setting.routerMode === "history" ? "/smartenergy/" : ""
    },
    production: {
        path: Setting.routerMode === "history" ? "/smartenergy/" : ""
    }
}

export const currentRouterBasePath = routerBasePath[environments]['path'];

// 导出路由 在 main.js 里使用
const router = new VueRouter({
    routes,
    mode: Setting.routerMode,
    base: currentRouterBasePath
});

//不需要鉴权的菜单
const notAuthRoute = ["/","/sysSetting/resetPassword"];
//路由鉴权
function routeAuth(to){
    if(!Setting.routeAuth){
        return true;
    }
    if(notAuthRoute.includes(to.path)){
        return true;
    }
    let menu = store.state.admin.menu.flattenMenu || [];
    if(menu.length > 0){
        //如果菜单不包含当前的路由，则跳转到403页面

        if(menu.find(m=>{
            let pathStr=''
            if(m.path.indexOf('?')>-1){
               pathStr=m.path.split('?')[0]
            }else{
               pathStr=m.path
            }
            return pathStr === to.path || (to.meta.origin || []).includes(pathStr)
        })){
            return true;
        }else{
            return false;
        }
    }else{
        return true;
    }
}

//当跳转到子用户的时候，需把子用户的id追加到路由的查询参数上
function getAppendArgument(to, from){
    let toQuery = JSON.parse(JSON.stringify(to.query));
    //如果不是跳转的子用户,则无需做任何追加
    let subUser = store.state.admin.subUser.user;
    if(!subUser.custId && !subUser.cliqueId){
        return;
    }
    //如果已经有,则无需追加
    if (to.query.subCustId || to.query.subCliqueId || to.query.subGroupCode || to.query.subCustomerType) {
        return;
    };
    if(subUser.custId){
        toQuery.subCustId = subUser.custId;
    }
    if(subUser.cliqueId){
        toQuery.subCliqueId = subUser.cliqueId;
    }
    if(subUser.groupCode){
        toQuery.subGroupCode = subUser.groupCode;
    }
    if(subUser.customerType){
        toQuery.subCustomerType = subUser.customerType;
    }
    return toQuery;
}

//改变页面的主题(判断是蓝色背景(有新旧两种样式)还是通用白色背景)
function changeTheme(meta){
    let theme = (meta || {}).theme;
    if(theme === "blue"){
        store.commit('setShowBlueLayout',true);
        store.commit('setShowBlueLayoutNew',false);
    }
    else if(theme === "blueNew"){
        store.commit('setShowBlueLayoutNew',true);
        store.commit('setShowBlueLayout',false);
    }
    else{
        store.commit('setShowBlueLayoutNew',false);
        store.commit('setShowBlueLayout',false);
    }
}

export {routeAuth};

/**
 * 路由拦截
 * 权限验证
 */

router.beforeEach((to, from, next) => {
    if (Setting.showProgressBar) iView.LoadingBar.start();
    changeTheme(to.meta);
    // 判断是否需要登录才可以进入
    if (to.matched.some(_ => _.meta.auth)) {
        // 这里依据 token 判断是否登录，可视情况修改
        const token = util.cookies.get('access_token');

        if (token && token !== 'undefined') {
            if(routeAuth(to)){
                let toQuery = getAppendArgument(to, from);
                //如果是根路由，需要根据当前账号来判断进入那个全景主页
                if(to.path === "/"){
                    let homePage = util.homePage.getHomePage();
                    router.push({path:homePage, query: toQuery || {}});
                }else{
                    if(toQuery){
                        next({path: to.path, query:toQuery});
                    }else{
                        next();
                    }
                }
            }else{
                next({path:'/403'});
            }
        } else {
            // 没有登录的时候跳转到登录界面
            // 携带上登陆成功之后需要跳转的页面完整路径
            store.dispatch("admin/account/logout", {redirect: to.fullPath});
        }
    } else {
        // 不需要身份校验 直接通过
        next();
    }
});

router.afterEach(to => {
    if (Setting.showProgressBar) iView.LoadingBar.finish();
    // 多页控制 打开新的页面
    store.dispatch('admin/page/open', to);
    // 更改标题
    util.title({
        title: to.meta.title
    });
    // 返回页面顶端
    window.scrollTo(0, 0);
});

export default router;
